import { reqLogin, reqLogout, reqGetInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
//项目的所有路由数组
import {constantRoutes,allAsyncRoutes} from '@/router/index'
//引入路由器
import router from 'vue-router'

//过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncR,routerArr){
  return asyncR.filter((route)=>{
    //先过滤一级路由
    if (routerArr.includes(route.name)){
      //递归过滤子集路由
      if(route.children && route.children.length>0){
        route.children = filterAsyncRoute(route.children,routerArr)
      }
      return true
    }
  })
}

const state ={
    token: getToken(),
    name: '',
    avatar: '',
    menuRoutes: [],
    result1: [],
}
const mutations = {
  RESET_STATE: (state) => {
    state.name = ''
    state.avatar = ''
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENUROUTES: (state, data) => {
    state.menuRoutes = data
  },
  SET_RESULT: (state,d)=>{
    state.result1 = d
  }
}

const actions = {
  //  用户登录
  async userLogin({dispatch,getters,state,commit},data){
    let result = await reqLogin(data)
    if(result.code == 20000){
      // 存token
      setToken(result.data.token)
      commit('SET_TOKEN', data.token)
      console.log('登录成功');
      return "ok"
    }else{
      return new Promise.reject(new Error(result.message))
    }
  },
  // 获取用户信息
  async getUserInfo({dispatch,commit,state,getters}){
    let result = await reqGetInfo()
    if(result.code == 20000){
      const { name, avatar,routes } = result.data
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      let result1 = filterAsyncRoute(allAsyncRoutes,routes)
      commit('SET_RESULT',result1)
      //左侧菜单组件
      //此处代码只能决定仓库存储当前用户全部需要路由对象,它只能决定左侧菜单展示的的数据
      //不能决定路由器管理路由(常量路由)
      //左侧菜单项的显示与隐藏
      commit('SET_MENUROUTES',[...constantRoutes,...result1])
      return 'ok'
    }else{
      return new Promise.reject(new Error(result.message))
    }
  },
  // 用户退出登录
  async logout({commit,dispatch,state,getters}){
    // 发送退出登录请求
    await reqLogout()
    // 删除Cookies中保存的token
    removeToken()
    // 提交重置用户信息的mutation
    state.token = ''
    state.name = ''
    state.avatar = ''
    //清空全部的异步路由
    // allAsyncRoutes.forEach((item)=>{
    //   router.removeRoute(item.name)
    // })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

